package chooongg.http

import chooongg.base.utils.withMain
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Deferred

suspend fun <RESPONSE> Deferred<RESPONSE>.response(callback: HttpCallback<RESPONSE>) {
    try {
        withMain { callback.onStart(this) }
        callback.response(await() ?: throw APIException(APIException.Type.EMPTY))
        withMain { callback.onEnd() }
    } catch (e: Throwable) {
        if (e is CancellationException) return
        withMain { callback.allotErrorDirection(APIException(e)) }
        withMain { callback.onEnd() }
    }
}